package com.woniu.service.Impl.homePage;

import com.alibaba.fastjson2.JSON;
import com.woniu.dao.homePage.GoodsLogDao;
import com.woniu.dao.homePage.GoodsReceptionDao;
import com.woniu.entity.Goods;
import com.woniu.service.homePage.IGoodsReceptionService;
import com.woniu.util.ResData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 凌雨
 * @data 2023/3/9 10:38
 */
@Service
public class GoodsReceptionServiceImpl implements IGoodsReceptionService {

    @Autowired
    private GoodsReceptionDao goodsReceptionDao;

    @Autowired
    private GoodsLogDao goodsLogDao;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 商品查询
     * @param param 传过来得到参数
     * @param phone 用户的手机号
     * @return
     */
    @Override
    public ResData<?> queryGoodsBy(String param, String phone) {
        String params = null;
        if (param != null && param.trim().length() > 0) {
            SetOperations<String, String> opsForSet = redisTemplate.opsForSet();
            opsForSet.add("search:"+phone, param);
            params = "%"+param+"%";
        }

        List<Goods> goodsList = goodsReceptionDao.queryGoodsByParam(params);

        return new ResData<>().ok(goodsList);
    }

    /**
     * 根据标签查询
     * @param tagId 传过来得到查询参数
     */
    @Override
    public ResData<?> queryGoodsByTagId(Integer tagId) {
        List<Goods> goodsTagList = goodsReceptionDao.queryGoodsByTagId(tagId);
        return new ResData<>().ok(goodsTagList);
    }

    /**
     * 查询所有商品
     *
     */
    @Override
    public ResData<?> queryGoodsAll() {

        String s = redisTemplate.opsForValue().get("goods");
        if(s != null){
            List<Goods> goodsList = JSON.parseArray(s, Goods.class);
            return new ResData<>().ok(goodsList);
        }

        List<Goods> goodsList = goodsReceptionDao.queryGoodsAll();
        if (goodsList == null){
            redisTemplate.opsForValue().set("goods","",2,TimeUnit.MINUTES);
            return new ResData<>().ok("无数据");
        }

        redisTemplate.opsForValue().set("goods",JSON.toJSONString(goodsList),1,TimeUnit.DAYS);

        return new ResData<>().ok(goodsList);
    }

    /**
     * 根据id查询商品信息
     * @param id
     * @return
     */
    @Override
    public ResData<?> queryGoodsById(Integer id, String phone) {
        if (phone == null) {
            return new ResData<>().ok(goodsReceptionDao.queryGoods(id));
        }
        goodsLogDao.addGoodsLog(id,phone);
        return new ResData<>().ok(goodsReceptionDao.queryGoods(id));
    }


}
